/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2020-12-02 17:52:57
 * @LastEditors: ding-cx
 * @LastEditTime: 2020-12-02 18:31:07
 * @Description: file content
 */
const captchapng = require('captchapng');
const Service = require("egg").Service;

/**
 *验证码服务类
 *
 * @class CaptchaService
 * @extends {Service}
 */
class CaptchaService extends Service {

    /**
     *输出验证码图片
     *
     * @memberof CaptchaService
     */
    async outputStrem() {
        const {
            ctx
        } = this;
        // ctx.body += "service";
        const word = parseInt(Math.random() * 9000 + 1000);
        var p = new captchapng(80, 30, word); // width,height,numeric captcha
        p.color(255, 255, 255, 255);  // First color: background (red, green, blue, alpha)
        p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)

        const isSave = await this.saveIndexStr(word);
        if (!isSave) return
        var img = p.getBase64();
        var imgbase64 = Buffer.from(img, 'base64');
        ctx.res.writeHead(200, {
            'Content-Type': 'image/png'
        });

        ctx.body = imgbase64;
    }

    /**
     *保存uuid，作为此验证码保存信息的唯一匹配凭证
     *
     * @memberof CaptchaService
     */
    async saveIndexStr(word = "") {
        const row = {
            cap_uuid: this.ctx.params.uuid,
            word,
            ip_address: this.ctx.request.ip
        }
        // console.log(row);
        const db = this.app.mysql.get("devdb");
        const result = await db.insert("sys_captcha", row)

        return result.affectedRows > 0;
    }
}

module.exports = CaptchaService;